/**********************************************************************/
/*
   Title: agents.do
   Author: Clotaire Boyer, Robbie Dulin
   Description: Runs voucher Exp Impact on Agents
*/
/**********************************************************************/



cap log close
local prefix: display %tdCYND td(`c(current_date)')
log using "$log/`prefix'_agents", replace text


clear
set more off
set seed 11022022

global finance_data "$cleaned/finance"


*** IE Treatment Effect on Agents
* winsorize continuous variables
u "$finance_data/mar19_village_IE_treats_lasso.dta", clear

gen agent_mar18 = agentsw_mar18 > 0

gen agent_total = agents_total > 0

foreach var in agents ratio agent {
  gen `var'W_total = `var'_total
  _pctile `var'_total, p(0.5 99.5)
  replace `var'W_total = `r(r1)' if `var'_total < `r(r1)'
  replace `var'W_total = `r(r2)' if `var'_total > `r(r2)' & `var'_total != .
  gen `var'W_mar18 = `var'_mar18
}
// summ agents_total agentsW_total
// summ ratio_total ratioW_total

* sample cuts
gen agents2 = agents_mar18 < 2
gen agents0 = agents_mar18 == 0
gen benef = min2_mar18 == 0 & beneficiaries < 500
gen all = 1
rename Kabupaten namakabupaten
est clear
eststo clear

/*  If needed depending on stata/pdslasso version:
encode idkab, gen(_idkab)
drop idkab
ren _idkab idkab
*/


* regression loop agents agentsW ratio ratioW both ratio250 min2
foreach var in agentsW agent {

  foreach sample in  agents0 all {
    ** regression with Lasso
    qui eststo `var'`sample'IE: pdslasso `var'_total treated (i.finalstratum log_beneficiaries `var'_mar18* *podes) ///
      if `sample' == 1, aset(i.finalstratum `var'_mar18*) cluster(idkab)
      qui summ `var'_total if e(sample) == 1 & treated == 0
      estadd scalar control_mean = r(mean)
      estadd scalar control_sd = r(sd)
      estadd scalar obs = e(N)
      estadd scalar select_num = e(xselected_ct) - e(xaset_ct)
      estadd local stratum = "Yes"
      estadd local lasso = "Yes"

    ** RI p-val
    randinference treated using "$importable/resample1000.dta", ///
      reg(reg `var'_total treated `e(xselected)' if `sample' == 1, vce(cluster idkab)) ///
      reps($RI) mergevar(namakabupaten) mergetype(m:1)
    matrix define pvalues = (`r(RIpval)')
    matrix colnames pvalues = treated
    est restore `var'`sample'IE
    estadd matrix pvalues

  }
}


local prefix: display %tdCYND td(`c(current_date)')
cap erase "$output/ster_files/20210226_finance/`prefix'_agents" // clear .ster if it already exists
qui estimates dir
foreach e in `r(names)' {
    quietly estimates restore `e'
    estimates title: `e'
    quietly estimates save "$output/ster_files/20210226_finance/`prefix'_agents", append
}

cap log close
